package com.zbdx.controller;

import com.zbdx.util.DruidUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/shopping/login")
public class LoginServlet extends HttpServlet {



    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取前端表单数据
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        // 数据库查询逻辑
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try {
            // 获取数据库连接
            conn = DruidUtil.getConnection();
            String sql = "SELECT * FROM users2 WHERE username = ? AND password = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, username);
            pstmt.setString(2, password);

            // 执行查询
            rs = pstmt.executeQuery();
            if (rs.next()) {
                // 登录成功，跳转到主页面
                HttpSession session = req.getSession();
                session.setAttribute("user", username);
                resp.sendRedirect("http://localhost:8080/OnlineShopping/shopping/productList?method=selectHeadByType");
            } else {
                // 登录失败，返回错误信息
                req.setAttribute("error", "Invalid username or password");
                req.getRequestDispatcher("login.jsp").forward(req, resp);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Database connection error");
        } finally {
            // 关闭资源，确保不会强制转换错误
            DruidUtil.close(conn);  // 关闭 Connection
        }
    }
}
